package com.rongshu.view.home.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.rongshu.R;
import com.rongshu.api.RetorfitService;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.FileUtils;
import com.rongshu.utils.RxHelper;
import com.rongshu.view.discovery.bean.ArticleDetaisRequest;
import com.rongshu.view.home.bean.AdvertResponse;
import com.rongshu.view.web.ActivityWeb;
import com.utils.DensityUtil;
import com.utils.FastClickUtils;
import com.utils.LogUtil;
import com.utils.SPUtils;
import com.utils.constants.SPKey;
import com.widget.titlebar.ImmersionBar;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;
import rx.Subscription;

/**
 * created by zhengweis on 2018/12/13.
 * description：
 */
public class SplashActivity extends Activity {
    @BindView(R.id.splash_img)
    ImageView splashImg;
    @BindView(R.id.skip)
    TextView skip;
    @BindView(R.id.bottom_view)
    RelativeLayout bottomView;
    //
    private String TAG = SplashActivity.class.getSimpleName();
    //本地广告图片Url
    private String localImgUrl;
    //本地广告图片路径
    private String advertPath = FileUtils.initPath();
    //用户是否已经查看过广告，用户已读广告，不需再次显示
    private boolean markReadAdvert = false;
    private Subscription subscribe;
    //本地缓存的广告图片
    private File localAdvertFile;
    //广告内容
    private AdvertResponse.ResponseBean advertBean;
    //onActivityForResult 的请求码
    private int mRequestCode = 1001;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        ButterKnife.bind(this);
        /*防止首次安装点击home键重新实例化*/
        if (!this.isTaskRoot()) {
            Intent intent = getIntent();
            if (intent != null) {
                String action = intent.getAction();
                if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(action)) {
                    finish();
                    return;
                }
            }
        }
        toHomeActivity();
//        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) splashImg.getLayoutParams();
//        int screenWidth = DensityUtil.getScreenWidth(this);
//        //根据ui给的宽高（375f:583f）比例，设置图片大小
//        float mHeight = screenWidth / 375f * 583f;
//        layoutParams.width = screenWidth;
//        layoutParams.height = (int) mHeight;
//        splashImg.setLayoutParams(layoutParams);
//        loadAdvertPicture();
    }

    private void loadAdvertPicture() {
        advertBean = getLocalAdvert();
        localImgUrl = advertBean != null ? advertBean.getImgUrl() : "";
        markReadAdvert = SPUtils.getPreferences(SPKey.MARK_READ_ADVERT, false);
        skip.setVisibility(markReadAdvert ? View.GONE : View.VISIBLE);
        LogUtil.d(TAG, localImgUrl);
        countdown();
        getAdvert();
        if (markReadAdvert) {//已读该广告
            LogUtil.d(TAG, "用户已查看广告，直接进入主页");
            FileUtils.deleteFile(new File(advertPath), false);
            toHomeActivity();
        } else {//未读该广告
            if (!TextUtils.isEmpty(localImgUrl)) {//本地保存了url
                loadLocalPicture();
            }
        }
    }

    /**
     * 加载本地图片
     */
    private void loadLocalPicture() {
        try {
            File file = new File(advertPath);
            if (file.exists()) {
                localAdvertFile = new File(file, "advert.jpg");
                if (localAdvertFile.exists()) {//本地图片有缓存
                    LogUtil.d(TAG, "直接从本地获取flie，并加载显示");
                    glideNoCache(localAdvertFile);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.splash_img, R.id.skip})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.splash_img://需记录广告的阅读状态
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                if (advertBean != null) {
                    if (advertBean.getType() == Constant.ADVERT_ARTICLE) {
                        ArticleDetaisRequest request = new ArticleDetaisRequest();
                        request.setContribute_id(advertBean.getId());
                        request.setType(Constant.FROM_RECOMMEND);
                        request.setTopic_id(0);
                        Intent mIntent = new Intent(this, SingleArticleDetailsActivity.class);
                        mIntent.putExtra(Constant.ARTICLE_DETAILS_REQUEST, request);
                        startActivityForResult(mIntent, mRequestCode);
                        SPUtils.putPreferences(SPKey.MARK_READ_ADVERT, true);
                    } else if (advertBean.getType() == Constant.ADVERT_H5) {
                        Intent intent = new Intent(this, ActivityWeb.class);
                        intent.putExtra(Constant.INTENT_H5, advertBean.getTypeUrl());
                        intent.putExtra(Constant.INTENT_TITLE, advertBean.getContentDescription());
                        startActivityForResult(intent, mRequestCode);
                        SPUtils.putPreferences(SPKey.MARK_READ_ADVERT, true);
                    }
                }
                break;
            case R.id.skip:
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                if (subscribe != null) {
                    subscribe.unsubscribe();
                }
                toHomeActivity();
                break;
        }
    }

    /**
     * 获取开屏广告
     */
    private void getAdvert() {
        Map<String, Object> map = new HashMap<>();
        map.put("random", 2);
        RetorfitService.getOpenAD(2, Common.encryptionSign(map))
                .subscribe(new Subscriber<AdvertResponse>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(AdvertResponse response) {
                        if (response != null && response.getResponse() != null) {
                            advertBean = response.getResponse();
                            String imgUrl = advertBean.getImgUrl();
                            if (markReadAdvert) {//已读该广告
                                if (!TextUtils.equals(imgUrl, localImgUrl)) {
                                    LogUtil.d(TAG, "广告更新了");
                                    bottomView.setVisibility(View.VISIBLE);
                                    //需重置用户的已读状态
                                    SPUtils.putPreferences(SPKey.MARK_READ_ADVERT, false);
                                    //更新本地缓存的广告图片
                                    urlGetFile(advertBean);
                                }
                            } else {//未读该广告
                                if (TextUtils.isEmpty(localImgUrl) || !TextUtils.equals(imgUrl, localImgUrl)) {
                                    bottomView.setVisibility(View.VISIBLE);
                                    LogUtil.d(TAG, "本地url不存在或广告更新了，通过网络url显示广告图片");
                                    if (splashImg != null) {
                                        Glide.with(SplashActivity.this).load(imgUrl).into(splashImg);
                                    }
                                    //缓存图片
                                    urlGetFile(advertBean);
                                } else if ((localAdvertFile == null || !localAdvertFile.exists())) {
                                    bottomView.setVisibility(View.VISIBLE);
                                    LogUtil.d(TAG, "本地file不存在，通过网络url显示广告图片");
                                    if (splashImg != null) {
                                        Glide.with(SplashActivity.this).load(imgUrl).into(splashImg);
                                    }
                                    //缓存图片
                                    urlGetFile(advertBean);
                                }
                            }
                        } else if (advertBean == null) {
                            toHomeActivity();
                        }
                    }
                });

    }

    private void urlGetFile(AdvertResponse.ResponseBean bean) {
        Glide.with(SplashActivity.this).asBitmap().load(bean.getImgUrl()).
                into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        LogUtil.d(TAG, "缓存图片到本地");
                        FileUtils.saveBitmap(resource, advertPath);
                        //更新本地保存的广告图片url，作为对比网络url、判断广告是否更新的依据
                        saveLocalAdvert(bean);
                    }
                });
    }

    /**
     * 倒计时
     */
    private void countdown() {
        //倒计时操作
        subscribe = RxHelper.countdown(3)
                .subscribe(new Subscriber<Integer>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(Integer integer) {
                        LogUtil.d("跳过 " + integer);
                        skip.setText("跳过 " + integer);
                        if (integer <= 1) {
                            toHomeActivity();
                        }
                    }
                });
    }

    private void toHomeActivity() {
        startActivity(new Intent(this, HomeActivity.class));
        finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (subscribe != null) {
            subscribe.unsubscribe();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == mRequestCode) {
            toHomeActivity();
        }
    }

    private void glideNoCache(File file) {
        bottomView.setVisibility(View.VISIBLE);
        RequestOptions options = new RequestOptions()
                .skipMemoryCache(true) // 不使用内存缓存
                .diskCacheStrategy(DiskCacheStrategy.NONE);
        Glide.with(this).load(file).apply(options).into(splashImg);
    }

    /**
     * 缓存广告信息
     */
    public void saveLocalAdvert(AdvertResponse.ResponseBean response) {
        String json = new Gson().toJson(response);
        SPUtils.putPreferences(SPKey.ADVERT, json);
    }

    /**
     * 获取缓存广告信息
     */
    public AdvertResponse.ResponseBean getLocalAdvert() {
        String json = SPUtils.getPreferences(SPKey.ADVERT, null);
        AdvertResponse.ResponseBean userInfo = null;
        if (!TextUtils.isEmpty(json)) {
            userInfo = new Gson().fromJson(json, AdvertResponse.ResponseBean.class);
        }
        return userInfo;
    }
}
